package com.yh.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yh.javabean.Role;
import com.yh.javabean.Users;
import com.yh.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.RolesAllowed;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Auther: als
 * @Date: 2024/5/27 - 05 - 27 - 16:16
 * @Description: com.yh.controller
 * @version: 1.0
 */
@Controller
@RequestMapping("/users")
public class UsersController {
    @Autowired
    UsersService usersService;

    @RolesAllowed("ADMIN")
   //查询用户列表
    @RequestMapping("/findAll")
    public String findAll(@RequestParam(value = "page", required = false, defaultValue = "1") int page,
                          @RequestParam(value = "limit", required = false, defaultValue = "5") int limit,
                          HttpServletRequest request) {
        PageHelper.startPage(page, limit);
        List<Users> all = usersService.findAll();
        PageInfo<Users> pageInfo = new PageInfo<>(all);
        request.setAttribute("pageInfo", pageInfo);
        return "/users/users-list";
    }

    @GetMapping("/add")
    public String addPage(HttpServletRequest request) {
        List<Role> allRole = usersService.findAllRole();
        request.setAttribute("roleList", allRole);
        return "/users/users-add";
    }
     @PostMapping("/add")
    public String add(Users users, int roleId) {
        usersService.addUsers(users, roleId);
        return "redirect:findAll";
    }

    //删除用户
    @GetMapping("/delete")
    public String delete(int id) {
       usersService.deleteUsers(id);
        return "redirect:findAll";
    }


    @GetMapping("/edit")
    public String editPage(int id,HttpServletRequest request){
        Users one = usersService.findOne(id);
        List<Role> roleList = usersService.findAllRole();
        request.setAttribute("users",one);
        request.setAttribute("roleList",roleList);
        return "/users/users-edit";
    }

    @PostMapping("/edit")
    public String editPage(Users users,int roleId) {
        usersService.editUsers(users,roleId);
        return "redirect:findAll";
    }
}
